<template>
  <view class="wrap">
    <view class="contentWrap">
      <img class="img" src="https://ainengli.hzjrsw.com/jkhx/test1.png" alt="" />
    </view>
    <view class="btnWrap">
      <view class="btn" v-if="isButtonDisabled == false" @tap="buyMember">
        <img class="img" src="@/static/image/hmm/bayImg.png" alt="" />
        <view class="btnNym">
          <text class="name">¥</text>
          <text class="num">{{ amount }}</text>
          <text class="name">/年</text>
        </view>
      </view>
      <view class="btn" v-else>
        <view class="btnNym">
          <text class="name">¥</text>
          <text class="num">{{ amount }}</text>
          <text class="name">/年</text>
        </view>
        <img class="img" src="@/static/image/hmm/bayImg.png" alt="" />
      </view>
    </view>
    <up-popup :show="isShow" :round="16" mode="bottom" closeable @close="isShow = false">
      <view class="title">请确认会员服务使用人</view>
      <view class="contentVisit">
        <text class="name">{{ userInfo.patName }}</text>
        <text class="name">{{ userInfo.gender == '女性' ? '女' : '男' }}</text>
        <text class="name" v-if="userInfo.age">{{ userInfo.age ? userInfo.age : '' }}岁</text>
        <text class="name" v-if="userInfo && userInfo.relation !== null">{{
          userInfo.relation
        }}</text>
      </view>
      <view class="pay">
        <view class="payName" @tap="immediatelyPay"> 立即支付 </view>
      </view>
    </up-popup>
  </view>
</template>

<script setup lang="ts">
import { reactive, ref } from 'vue'
import { paying, getProduct, orderStatus } from '@/api/hmm'
import { onShow, onLoad, onUnload } from '@dcloudio/uni-app'
import { base_info } from '@/api/moreMessage'
import { subscribeMessage } from '@/api/index'
import store from '@/store'
const state = reactive({
  timeQuestions: null
})
const userInfo = ref({})
const userInfoNew = ref({})
const productObj = ref({})
const isShow = ref(false)
const bizOrderNo = ref('')
const sourceTarget = ref('')
const sourceId = ref('')
const amount = ref(0)
const isButtonDisabled = ref(false)
const isstop = ref(false)
onLoad((options) => {
  if (options.source == 'sourceHealthManageDetail') {
    sourceTarget.value = options.source
    sourceId.value = options.id
  } else {
    sourceTarget.value = options.source
  }
  userInfo.value = uni.getStorageSync('userInfo')
    ? JSON.parse(uni.getStorageSync('userInfo')).patientInfo
    : {}
  userInfoNew.value = uni.getStorageSync('userInfo')
    ? JSON.parse(uni.getStorageSync('userInfo'))
    : {}
})
onShow(() => {
  init()
})
onUnload(() => {
  //   uni.showLoading({
  //     title: '加载中'
  //   })
  clearInterval(state.timeQuestions)
  state.timeQuestions = null
})
const init = () => {
  uni.showLoading({
    title: '加载中'
  })
  getProduct().then((res) => {
    if (isstop.value == false) {
      uni.hideLoading()
    }
    if (res.code == 0) {
      productObj.value = res.data
      amount.value = res.data && res.data.amount ? res.data.amount.toFixed(2) : 0
    }
  })
}
const buyMember = () => {
  isShow.value = true
}
const immediatelyPay = () => {
  let param = {
    productId: productObj.value.productId,
    openId: userInfoNew.value.openId,
    channel: 'wechat_pay',
    method: 'jsapi',
    userId: userInfoNew.value.userId,
    phone: userInfoNew.value.phone,
    empi: userInfo.value.empi,
    patName: userInfo.value.patName
  }
  isShow.value = false
  isButtonDisabled.value = true
  uni.showLoading({
    title: '加载中'
  })
  setTimeout(() => {
    paying(param).then((res) => {
      uni.hideLoading()
      let payParam = JSON.parse(res.data.payBody)
      bizOrderNo.value = res.data.bizOrderNo
      uni.requestPayment({
        provider: 'wxpay',
        timeStamp: payParam.timeStamp,
        nonceStr: payParam.nonceStr,
        package: payParam.package,
        signType: payParam.signType,
        paySign: payParam.paySign,
        success: function (res) {
          isstop.value = true
          uni.showToast({
            title: '支付成功',
            icon: 'none',
            duration: 2000
          })
          // 点击按钮订阅消息
          const templat_id = 'oxk-aA4WH8sIHnY5kwTg4_QrFoQBX9H-tTqFUsWy_o4'
          uni.requestSubscribeMessage({
            tmplIds: [templat_id],
            success(res) {
              if (res.errMsg === 'requestSubscribeMessage:ok') {
                // 订阅成功，可以在这里触发订阅消息的后续操作
                pushMessage(res[templat_id])
              }
            },
            fail(err) {
              // 订阅失败，可以在这里处理订阅失败的情况
              uni.showToast({
                title: '消息订阅发送失败!',
                icon: 'error',
                duration: 2000
              })
            },
            complete(fis) {
              loopTime()
            }
          });
          console.log('success:' + JSON.stringify(res))
        },
        fail: function (err) {
          isstop.value = false
          isButtonDisabled.value = false
          // uni.showToast({
          //   title: '支付失败,请重试',
          //   icon: 'none',
          //   duration: 2000
          // })
          console.log('fail:' + JSON.stringify(err))
        }
      })
    })
  }, 200)
}
const loopTime = () => {
  let s = 0
  uni.showLoading({
    title: '加载中'
  })
  state.timeQuestions = setInterval(() => {
    s++
    if (s >= 2) {
      s = 0
      orderStatusFun()
    }
  }, 1000)
}
const orderStatusFun = () => {
  let param = bizOrderNo.value
  orderStatus(param).then((res) => {
    isstop.value = true
    if (res.data.payState == 'PROGRESS') {
    } else if (res.data.payState == 'SUCCESS') {
      let params = {
        userId: userInfoNew.value.userId,
        empi: userInfo.value.empi
      }
      base_info(params).then((res) => {
        const info = Object.assign({}, JSON.parse(uni.getStorageSync('userInfo')))
        info.patientInfo = res.data
        store.commit('SET_USERINFO', info)
        clearInterval(state.timeQuestions)
        state.timeQuestions = null
        // setTimeout(() => {
          isstop.value = false
          isButtonDisabled.value = false
          if (sourceTarget.value == 'sourceIndex') {
            if (info.patientInfo.questionState == true) {
              uni.redirectTo({ url: '/packA/pages/questionaire/risk' })
            } else {
              uni.redirectTo({ url: '/packA/pages/questionaire/enter' })
            }
          } else if (sourceTarget.value == 'sourceHealthManageDetail') {
            uni.redirectTo({ url: '/packA/pages/healthManage/detail?id=' + sourceId.value })
          } else if (sourceTarget.value == 'greenWay') {
            uni.redirectTo({ url: '/packA/pages/healthManage/greenWay' })
          } else if (sourceTarget.value == 'im') {
            uni.switchTab({
              url: '/pages/im/pages/Conversation/index'
            })
          } else if (sourceTarget.value == 'physicalList') {
            uni.redirectTo({ url: '/packA/pages/report/physicalList' })
          }
        // }, 2000)
      })
    }
    // else if (res.data.payState == 'REFUNDED' || res.data.payState == 'CLOSE') {
    else {
      //   uni.showToast({
      //     title: '支付失败',
      //     icon: 'none'
      //   })
      clearInterval(state.timeQuestions)
      state.timeQuestions = null
    }
  })
}

const pushMessage = (status: string) => {
    // 订阅成功提醒后端
    let params = {
      tempId: 'oxk-aA4WH8sIHnY5kwTg4_QrFoQBX9H-tTqFUsWy_o4',
      openId: userInfoNew.value.openId,
      empi: userInfo.value.empi,
      state: status,
      bizNo: bizOrderNo.value
    }
    subscribeMessage(params).then((res) => {
      console.log('订阅成功推送', params, res)
    })
}
</script>

<style lang="scss" scoped>
.wrap {
  min-height: 100vh;
  .contentWrap {
    padding-bottom: 138rpx;
    .img {
      width: 100%;
      height: 1380rpx;
      display: block;
      margin-top: 50rpx;
    }
  }
  .btnWrap {
    position: fixed;
    bottom: 0;
    left: 0;
    width: 100%;
    background: linear-gradient(to bottom, #fcf0e2, #ffffff);
    border-top-left-radius: 32rpx;
    border-top-right-radius: 32rpx;
    padding-top: 32rpx;
    padding-bottom: constant(safe-area-inset-bottom);
    padding-bottom: env(safe-area-inset-bottom);
    // padding-bottom: calc(24rpx + constant(safe-area-inset-bottom));
    // padding-bottom: calc(24rpx + env(safe-area-inset-bottom));
    .btn {
      padding: 0rpx 32rpx;
      position: relative;
      .img {
        height: 98rpx;
        width: 100%;
        display: block;
      }
      .btnNym {
        position: absolute;
        top: calc(50% - 12rpx);
        transform: translateY(-50%);
        left: 80rpx;
        .name {
          display: inline-block;
          vertical-align: middle;
          font-size: 28rpx;
          color: rgba(255, 255, 255, 0.7);
        }
        .num {
          font-weight: 700;
          font-size: 48rpx;
          color: #fff;
          display: inline-block;
          vertical-align: middle;
          margin: 0 8rpx;
        }
      }
    }
  }
  ::v-deep .u-popup {
    .title {
      height: 108rpx;
      line-height: 108rpx;
      text-align: center;
      font-weight: 700;
      font-size: 32rpx;
      color: #222;
      border-bottom: 1px solid #e5e6eb;
    }
    .contentVisit {
      padding: 22rpx 32rpx;
      margin: 32rpx;
      background: #fafafa;
      border-radius: 8rpx;
      .name {
        display: inline-block;
        vertical-align: middle;
        font-size: 30rpx;
        color: #222;
        margin-right: 24rpx;
        &:nth-child(4) {
          padding: 2rpx 24rpx;
          background: #00d1b6;
          color: #fff;
          font-size: 24rpx;
          border-radius: 18rpx;
          margin-right: 0;
        }
      }
    }
    .pay {
      padding: 24rpx 32rpx 32rpx;
      .payName {
        height: 88rpx;
        line-height: 88rpx;
        background: #00d1b6;
        color: #fff;
        font-weight: 700;
        font-size: 32rpx;
        text-align: center;
        border-radius: 44rpx;
      }
    }
  }
  ::v-deep .u-icon__icon {
    font-size: 32rpx !important;
    line-height: 50rpx !important;
  }
}
</style>
